package com.komodo.island.gdx.game.komodomove;

import android.content.Context;
import android.os.PowerManager;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.actors.Image;
import com.komodo.island.gdx.Art;
import com.komodo.island.gdx.Constants;
import com.komodo.island.gdx.KomodoIsland;
import com.komodo.island.gdx.Persistence;
import com.komodo.island.gdx.dialog.LoseDialog;
import com.komodo.island.gdx.dialog.WinDialog;
import com.komodo.island.gdx.game.Time;
import com.komodo.island.gdx.screen.GameScreen;
import com.komodo.island.gdx.screen.Screen;

public class KomodoMove extends GameScreen {
	public static final int SPEED = 5;
	public static final int PLAY = 0;
	public static final int LOSE = 1;
	public static final int WIN = 2;
	public static final boolean LEFT = true;
	public static final boolean RIGHT = false;
	public static int POSX = 25;
	public static int POSY = 40;

	private Pixmap path;
	private Texture komodoMoveTexture;
	private Sprite komodoSprite;
	private Sprite komodoCollisionSprite;
	private Texture pathTexture;
	private Sprite pathSprite;
	private float degree;
	private float accelX;
	private float accelY;
	private float accelZ;
	private float azimuth;
	private float pitch;
	private float roll;
	private Time time;
	private double second;
	private int state;
	private boolean move;
	private Sound out;
	private Sound finishSound;
//	private Time gameTime;

	public void init(KomodoIsland komodoIsland, Texture texture) {
		// TODO Auto-generated method stub
		super.init(komodoIsland, texture);
		previousScreen = komodoIsland.scientistScreen;

		// PowerManager pm = (PowerManager)
		// getSystemService(Context.POWER_SERVICE);
		// PowerManager.WakeLock wl =
		// pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
		// wl.acquire();
		//
		// wl.release();

	}

	public boolean isOutOfBound() {
		return (Integer.toHexString(
				path.getPixel((int) komodoCollisionSprite.getX(),
						(int) komodoCollisionSprite.getY())).length() < 6
				|| Integer.toHexString(
						path.getPixel((int) komodoCollisionSprite.getX()
								+ (int) komodoCollisionSprite.getWidth(),
								(int) komodoCollisionSprite.getY())).length() < 6
				|| Integer.toHexString(
						path.getPixel(
								(int) komodoCollisionSprite.getX(),
								(int) komodoCollisionSprite.getY()
										+ (int) komodoCollisionSprite
												.getHeight())).length() < 6 || Integer
				.toHexString(
						path.getPixel(
								(int) komodoCollisionSprite.getX()
										+ (int) komodoCollisionSprite
												.getWidth(),
								(int) komodoCollisionSprite.getY()
										+ (int) komodoCollisionSprite
												.getHeight())).length() < 6);
	}

	public void Move() {
		komodoCollisionSprite.setPosition(
				komodoCollisionSprite.getX()
						+ ((float) Math.cos(Math.toRadians(degree)) * SPEED),
				komodoCollisionSprite.getY()
						+ ((float) Math.sin(Math.toRadians(degree)) * SPEED));
		pathSprite.setPosition(
				pathSprite.getX()
						- ((float) Math.cos(Math.toRadians(degree)) * SPEED),
				pathSprite.getY()
						+ ((float) Math.sin(Math.toRadians(degree)) * SPEED));
		// System.out.println("Cos A : " + Math.cos(Math.toRadians(degree))
		// + "Sin A : " + Math.sin(Math.toRadians(degree)));
	}

	public float pitchConvert() {
		if (Gdx.input.getRoll() > 0) {
			return (90 + Gdx.input.getPitch());
		} else {
			return (-(90 + Gdx.input.getPitch()));
		}
	}

	@Override
	protected void onGameLoading() {
		// TODO Auto-generated method stub
		if (out == null) {
			out = Gdx.audio.newSound(Gdx.files.internal("sfx/move/out.wav"));
		}

		if (finishSound == null) {
			finishSound = Gdx.audio.newSound(Gdx.files
					.internal("sfx/move/finish.wav"));
		}

		if (komodoIsland.move == null) {
			komodoIsland.move = Gdx.audio.newMusic(Gdx.files
					.internal("bgm/move.mp3"));
			komodoIsland.move.setLooping(true);
			komodoIsland.move.setVolume(0.5f);
		}

		if (Persistence.sound) {
			try {
				if (!komodoIsland.move.isPlaying()) {
					komodoIsland.move.play();
				}
			} catch (Exception e) {

			}
		}

		if (time == null)
			time = new Time(1, 30);
//		if (gameTime == null)
//			gameTime = new Time(1, 30);

		
		
		if (path == null)
			path = new Pixmap(Gdx.files.internal("move2.png"));
		if (pathTexture == null)
			pathTexture = new Texture(Gdx.files.internal("move1.jpg"));

		// if (pathSprite == null) {
		pathSprite = new Sprite(pathTexture, 0, 0, pathTexture.getWidth(),
				pathTexture.getHeight());

		// }

		if (komodoMoveTexture == null)
			komodoMoveTexture = new Texture(Gdx.files.internal("move3.png"));

		// if (komodoCollisionSprite == null) {
		komodoCollisionSprite = new Sprite(komodoMoveTexture, 100, 50,
				Constants.GAME_HEIGHT / 8, Constants.GAME_HEIGHT / 8);

		// }

		// if (komodoSprite == null) {
		komodoSprite = new Sprite(komodoMoveTexture, 200, 0, 100, 50);

		// }

		if (winDialog == null)
			this.winDialog = new MoveWinDialog(480, 320, true, this,
					komodoIsland.dialogTexture,komodoIsland);
		if (loseDialog == null)
			this.loseDialog = new MoveLoseDialog(480, 320, true, this,
					komodoIsland.dialogTexture,komodoIsland);

		
	}

	@Override
	protected void onGameLose() {
		// TODO Auto-generated method stub
		// System.out.println("Lose");

	}

	@Override
	public void hide() {
		// TODO Auto-generated method stub
		super.hide();
		try {
			if (Persistence.sound) {
				if (komodoIsland.move.isPlaying()) {
					komodoIsland.move.stop();
				}
			} else {

			}
		} catch (Exception e) {

		}
	}

	@Override
	public void show() {
		// TODO Auto-generated method stub
		super.show();
		try {
			if (Persistence.sound) {
				if (!komodoIsland.move.isPlaying()) {
					komodoIsland.move.play();
				}
			} else {

			}
		} catch (Exception e) {

		}
	}

	@Override
	protected void onGamePause() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onGameRunning() {
		// TODO Auto-generated method stub

		camera.update();
		batch.setProjectionMatrix(camera.combined);
		if (state == PLAY) {
//			gameTime.runTime();
			time.runTime();
			if (time.getSecond() == 0 && time.getMinute() == 0) {
//				time.setMinute(1);
				setGameToLose();
			}
			if (second < time.getSecond()) {
				second = 59;
			}
			if (second - time.getSecond() >= 0.09) {
				Move();
				second = time.getSecond();
				if (move == LEFT) {
					komodoSprite.setRegion(300, 0, 100, 50);
					move = RIGHT;
				} else {
					komodoSprite.setRegion(200, 0, 100, 50);
					move = LEFT;
				}
			}
			if (isOutOfBound()
					|| (time.getSecond() == 0 && time.getMinute() == 0)) {
				if (Persistence.sound)
					out.play(1);
				state = LOSE;
				komodoSprite.setRegion(0, 0, 100, 50);
				komodoCollisionSprite.setBounds(komodoCollisionSprite.getX(),
						komodoCollisionSprite.getY(),
						Gdx.graphics.getWidth() / 8,
						Gdx.graphics.getHeight() / 8);
				setGameToLose();
			}
			batch.begin();
			pathSprite.draw(batch);
			komodoSprite.draw(batch);
			batch.end();
			Art.drawString("Time : " + time.getMinute() + " : " +Art.decimal2.format(time.getSecond()),
					0, -2);

			// User Input
			if (Math.abs(accelZ) > accelX && Math.abs(accelZ) > accelY) {
				if (Gdx.input.getAzimuth() > azimuth + 1
						|| Gdx.input.getAzimuth() < azimuth - 1) {
					komodoSprite.rotate(degree);
					if (accelZ > 0) {
						degree -= Gdx.input.getAzimuth() - azimuth;
					} else {
						degree += Gdx.input.getAzimuth() - azimuth;
					}
					azimuth = Gdx.input.getAzimuth();
					komodoSprite.rotate(-degree);
				} // }
			} else {
				// if (Gdx.input.getPitch() > pitch + 3 || Gdx.input.getPitch()
				// < pitch - 3){
				if (pitchConvert() > pitch + 1 || pitchConvert() < pitch - 1) {
					komodoSprite.rotate(degree);
					degree -= pitchConvert() - pitch;
					pitch = pitchConvert();
					roll = Gdx.input.getRoll();
					komodoSprite.rotate(-degree);
				}
			}
			if (komodoCollisionSprite.getX() > 1000
					|| komodoCollisionSprite.getY()
							+ komodoCollisionSprite.getHeight() > 1000) {
				if (Persistence.sound)
					finishSound.play(1);
				score += time.getSecond() * 1000;
				setGameToWin();
				
				state = WIN;
			}
//			if (gameTime.getSecond() == 0 && gameTime.getMinute() == 0) {
////				gameTime.setMinute(1);
//				setGameToLose();
//			}
			
			
		} else if (state == WIN) {
			// setGameToWin();
			// onGameWin();
		} else {
			time.setSecond(2);
			time.runTime();
			if (time.getSecond() == 0) {
				// onGameLose();
				// setGameToLose();
			}
			batch.begin();
			pathSprite.draw(batch);
			komodoSprite.draw(batch);
			batch.end();
		}
	}

	@Override
	protected void onGameStart() {
		// TODO Auto-generated method stub
		move = true;
		state = PLAY;
		time.setMinute(1);
		time.setSecond(30);
	
		score = 0;
		second = 30;
		pathSprite
				.setBounds((Constants.GAME_WIDTH / 2) - POSX,
						(-pathTexture.getHeight())
								+ (Constants.GAME_HEIGHT / 2) + POSY,
						pathTexture.getWidth(), pathTexture.getHeight());
		komodoCollisionSprite.setBounds(POSX - Constants.GAME_HEIGHT / 16, POSY
				- Constants.GAME_HEIGHT / 16, Constants.GAME_HEIGHT / 8,
				Constants.GAME_HEIGHT / 8);

		// komodoSprite.setRegion( 200, 0, 100, 50);
		komodoSprite.setBounds((Constants.GAME_WIDTH / 2) - 50,
				(Constants.GAME_HEIGHT / 2) - 25, 100, 50);
		komodoSprite.setOrigin(komodoSprite.getWidth() / 2,
				komodoSprite.getHeight() / 2);
		try {
			komodoIsland.wl.acquire(90000);
		} catch (Exception e) {

		}
		
		
	}

	@Override
	protected void onGameWin() {
		// TODO Auto-generated method stub
		// System.out.println("Win");
	}

	// @Override
	// protected boolean onGameStartAnimation() {
	// // TODO Auto-generated method stub
	// return false;
	// }

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
		super.dispose();

	}

	@Override
	public void cleanResScreen() {
		// TODO Auto-generated method stub
		super.cleanResScreen();
		try {
			path.dispose();
			pathTexture.dispose();
			komodoMoveTexture.dispose();
			path = null;
			pathTexture =null;
			komodoMoveTexture =null;
		} catch (Exception e) {

		}
	}
	@Override
	public void exitScreen() {
		// TODO Auto-generated method stub
		try {
			path.dispose();
			pathTexture.dispose();
			komodoMoveTexture.dispose();
			path = null;
			pathTexture =null;
			komodoMoveTexture =null;
		} catch (Exception e) {

		}
		super.exitScreen();
	}

	class MoveWinDialog extends WinDialog {

		public Image finish;

		public MoveWinDialog(float width, float height, boolean stretch,
				Screen screen, Texture texture,KomodoIsland komodoIsland) {
			super(width, height, stretch, screen, texture,komodoIsland);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void init() {
			// TODO Auto-generated method stub
			super.init();
			finish = new Image("finish", new TextureRegion(
					screen.komodoIsland.additionTexture, 480, 440, 96, 96));
		}

		@Override
		public void addElements() {
			// TODO Auto-generated method stub
			super.addElements();
			addActor(finish);
		}

		@Override
		public void setThePosition() {
			// TODO Auto-generated method stub
			super.setThePosition();
			finish.x = siKomo.x;
			finish.y = siKomo.y;

		}

	}

	class MoveLoseDialog extends LoseDialog {

		public Image finish;

		public MoveLoseDialog(float width, float height, boolean stretch,
				Screen screen, Texture texture,KomodoIsland komodoIsland) {
			super(width, height, stretch, screen, texture,komodoIsland);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void init() {
			// TODO Auto-generated method stub
			super.init();
			finish = new Image("finish", new TextureRegion(
					screen.komodoIsland.additionTexture, 480, 536, 96, 96));
		}

		@Override
		public void addElements() {
			// TODO Auto-generated method stub
			super.addElements();
			addActor(finish);
		}

		@Override
		public void setThePosition() {
			// TODO Auto-generated method stub
			super.setThePosition();
			finish.x = siKomo.x;
			finish.y = siKomo.y;

		}
	}
	
	@Override
	protected boolean onGameStartAnimation() {
		// TODO Auto-generated method stub
		currTime = System.currentTimeMillis();
		startDialog.draw();

		Art.drawString(startDialog.getSpriteBatch(), "" + bestScore, 178, 0);
		if (currTime - startTime <= 1000) {
			// Art.drawString("3", 240 - 32, 160 - 32);
			startDialog.getSpriteBatch().begin();
			startDialog.getSpriteBatch().draw(komodoIsland.startupAnimation[0],
					240 - 270 / 2, 160 - 270 / 2);
			startDialog.getSpriteBatch().end();

			return true;
		} else if (currTime - startTime > 1000 && currTime - startTime <= 2000) {
			// Art.drawString("2", 240 - 32, 160 - 32);
			startDialog.getSpriteBatch().begin();
			startDialog.getSpriteBatch().draw(komodoIsland.startupAnimation[1],
					240 - 270 / 2, 160 - 270 / 2);
			startDialog.getSpriteBatch().end();

			return true;
		} else if (currTime - startTime > 2000 && currTime - startTime <= 3000) {
			// Art.drawString("1", 240 - 32, 160 - 32);
			startDialog.getSpriteBatch().begin();
			startDialog.getSpriteBatch().draw(komodoIsland.startupAnimation[2],
					240 - 270 / 2, 160 - 270 / 2);
			startDialog.getSpriteBatch().end();
			return true;
		} else {
			degree = 0;
			accelX = Gdx.input.getAccelerometerX();
			accelY = Gdx.input.getAccelerometerY();
			accelZ = Gdx.input.getAccelerometerZ();
			azimuth = Gdx.input.getAzimuth();
			roll = Gdx.input.getRoll();
			pitch = pitchConvert();
			return false;
		}
	}
}
